#include "QGLRendererThread.h"

#include "MathUtil.h"

#include <QtCore/QDateTime>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <iostream>


namespace jcrada {

    QGLRendererThread::QGLRendererThread( ) : QThread( ) {
        this->_init();
        int x = 0, y = 0, w = 640, h = 480;
        x = (QApplication::desktop()->width() / 2.0) - (w / 2.0);
        y = (QApplication::desktop()->height() / 2.0) - (h / 2.0);
        setRenderer(new QGLRenderer(NULL, x, y, w, h));
    }

    QGLRendererThread::QGLRendererThread( QGLRenderer* renderer ) {
        this->_init();
        setRenderer(renderer);
    }

    void QGLRendererThread::_init( ) {
        _renderer = NULL;
    }

    QGLRendererThread::~QGLRendererThread( ) {
        delete _renderer;
    }

    void QGLRendererThread::setRenderer( QGLRenderer* renderer ) {
        if (this->_renderer) {
            QObject::disconnect(this, SIGNAL(render()),
                    this->_renderer, SLOT(updateGL()));
        }
        this->_renderer = renderer;
        QObject::connect(this, SIGNAL(render()),
                this->_renderer, SLOT(updateGL()),
                Qt::QueuedConnection);
    }

    void QGLRendererThread::notify( ) {
        if (getRenderer().isRenderable() && !this->isRunning()) {
            start();
        }
    }

    void QGLRendererThread::stop( ) {
        getRenderer().setRenderable(false);
        wait();
    }

    void QGLRendererThread::run( ) {
        BDEBUG("QGLRendererThread::run()");
        QTime time;
        time.start();
        long sleep = 0;
        while (getRenderer().isRenderable()) {
            time.restart();
            emit render();
            sleep = (1000.0 / getRenderer().getFrameRate()) - time.elapsed();
            if (sleep > 0) {
                this->msleep(sleep);
            }
        }
    }

    int QGLRendererThread::main( int argc, char** argv ) {
        QApplication app(argc, argv);
        QGLRendererThread r;
        r.getRenderer().setFrameRate(6);
        r.getRenderer().show();
        r.start();
        //        GLWidget widget(NULL);
        //        widget.show();
        //        widget.startRendering();
        return app.exec();
    }

}
